package com.tunnel.home.filter;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.axe.bean.mvc.Handler;
import org.axe.bean.mvc.Handler.ActionParam;
import org.axe.bean.mvc.Header;
import org.axe.bean.mvc.Param;
import org.axe.exception.RestException;
import org.axe.helper.ioc.BeanHelper;
import org.axe.interface_implement.mvc.HeaderFilter;

import com.tunnel.home.dao.UserDao;
import com.tunnel.home.entity.User;

public class AuthFilter extends HeaderFilter{

	@Override
	public Header[] headers() {
		return new Header[]{new Header("TUNNEL-TOKEN")};
	}

	@Override
	public boolean doFilter(Header[] headers, HttpServletRequest request, HttpServletResponse response, Param param,
			Handler handler) {
		String token = "";
		if(headers != null && headers.length>0){
			token = headers[0].getValue();
		}
		
		//检查token是否还有效，如果没效果了，返回401
		UserDao userDao = BeanHelper.getBean(UserDao.class);
		User user = userDao.getUserByToken(token);
		if(user == null){
			throw new RestException(RestException.SC_UNAUTHORIZED, "请登录！");
		}
		
		List<Object> actionParamList = param.getActionParamList();
		List<ActionParam> defineParamList = handler.getActionParamList();
		int userParamIndex=-1;
		for(int i=0;i<defineParamList.size();i++){
			ActionParam ap=defineParamList.get(i);
			if(ap.getParamType().equals(User.class)){
				userParamIndex = i;
				break;
			}
		}
		if(userParamIndex >= 0){
			actionParamList.set(userParamIndex, user);
		}
		
		return true;
	}

}
